//
//  API_Comment.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import Moya

enum API_Comment {
    /// 获取评论列表
    case getCommentList(String, Int)
    /// 添加评论
    case addComment(String, String)
}

let comment_timeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<API_Comment>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 5
        done(.success(request))
    }catch {
        return
    }
}

let provider_comment = MoyaProvider<API_Comment>(requestClosure: comment_timeoutClosure)

extension API_Comment: TargetType {
    var baseURL: URL {
        return URL(string: server.APIHost)!
    }
    
    var path: String {
        switch self {
        case .getCommentList(_, _):
            return "/Article/comments"
        case .addComment(_, _):
            return "/Article/comment"
        }
    }
    
    var method: Moya.Method {
        return .post
    }
    
    var parameterEncoding: ParameterEncoding {
        return JSONEncoding.default
    }
    
    var sampleData: Data {
        return "test".data(using: String.Encoding.utf8)!
    }
    
    var task: Task {
        var ps: [String: Any] = ["ver": getAPPVersion(), "channel": "ios", "third_channel": "apple", "timestamp": Date().timeStamp, "userId": getUser()?.userId ?? "", "uuid": getKeyUUId(), "user_channel": getADID()]
        switch self {
        case .getCommentList(let bid, let page):
            ps["bookId"] = bid
            ps["page"] = page
            ps["num"] = 10
        case .addComment(let bid, let content):
            ps["bookId"] = bid
            ps["comment"] = content
            ps["userName"] = getUser()?.userName
        }
        return .requestParameters(parameters: ps, encoding: JSONEncoding.default)
    }
    
    var headers: [String : String]? {
        return ["content-type": "application/json; charset=UTF-8"]
    }
}
